#! /user/bin/python3
# coding-utf-8
# @Time = 2025/4/9 10:51
# @Author:Poolaris
import pytest
import re

from config.driver_config import DriverConfig
from common.report_add_img import add_img_2_report
from common.process_redis import Process
from common.yaml_config import GetConf
from common.qywx_talk import send_qywx_talk_msg


def pytest_collection_finish(session):
    # 所有用例的个数
    total = len(session.items)
    # 重置用例进度和失败用例名称
    Process().reset_all()
    # 初始化进度
    Process().init_process(total)


@pytest.fixture(scope='class')
def driver():
    global get_driver
    get_driver = DriverConfig().driver_config()
    yield get_driver
    get_driver.quit()


@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    # 获取钩子方法的调用结果
    out = yield
    # 从钩子方法的调用结果中获取测试结果
    report = out.get_result()
    report.description = str(item.function.__doc__)

    if report.when == "call":
        # instance = item.instance
        if report.failed:
            # if hasattr(instance, 'driver'):
                # driver = instance.driver
            # 失败了就截图
            add_img_2_report(get_driver, "失败截图", need_sleep=False)
            # 更新失败用例个数
            Process().update_fail()
            # 增加失败用例名称
            Process().insert_into_fail_testcase_names(report.description)
        elif report.passed:
            Process().update_success()
        else:
            pass

        process = Process().get_process()
        print(process)

        webhook = GetConf().get_qywx_webhook()
        # 如果report.description存在，则仅保留中文字符
        if report.description == "None":
            report.description = "该用例没有添加描述:" + item.name
        else:
            report.description = re.sub(r'[^\u4e00-\u9fa5]', '', report.description)
            print("进入\"\"\"分支，修改后描述为", report.description, "。类型为：", type(report.description), "描述长度：",
                  len(report.description))

        send_qywx_talk_msg(webhook,
                           "测试用例:"
                           + report.description
                           + "\n测试结果: "
                           + report.outcome
                           + "\n自动化测试进度: "
                           + process
                           )
